package com.loong.game2048.controller;

import com.loong.game2048.Exception.BizException;
import com.loong.game2048.annotation.Authorize;
import com.loong.game2048.module.ResultCode;
import com.loong.game2048.module.vo.Result;
import com.loong.game2048.util.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author lyx
 * @date 2020/5/9 16:29
 */
@RestController
public class FileController {

    @Value("${web.upload-path}")
    private String path;

    @Value("${web.url}")
    private String url;


    /**
     * 上传图片
     * @param file
     * @return 返回图片名称
     */
//    @Authorize
    @PostMapping("/uploadPicture")
    public Result<String> uploadPicture(@RequestParam("photo") MultipartFile file) {
        Result<String> result=new Result<>();
        if(file==null){
            result.setMsg("文件为空");
            result.setCode(300);
            return result;
        }
        String fileName=file.getOriginalFilename();
        if(!FileUtils.judgeFileType(fileName.substring(fileName.lastIndexOf(".")+1))){
            throw new BizException("文件格式错误");
        }
        String filePath=path+"photo/";
        String fileNewName= FileUtils.getFileNewName(file.getOriginalFilename());
        try {
            FileUtils.upload(file.getBytes(),filePath,fileNewName);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg("下载失败");
            result.setCode(ResultCode.UNSPECIFIED);
            return result;
        }
        result.setCode(ResultCode.SUCCESS);
        result.setMsg("上传成功");
        result.setData(fileNewName);
        return result;

    }

    /**
     * 将图片文件从服务器删除
     * @param photoName 图片访问地址
     * @return  result
     */
    @Authorize
    @GetMapping("/deletePicture")
    public  Result deletePicture(@RequestParam("photo")  String photoName){
        Result result =new Result();
        String photo=photoName.substring(photoName.lastIndexOf("/")+1);
        String filePath=path+"photo/"+photo;
        FileUtils.deleteFile(filePath);
        result.setCode(ResultCode.SUCCESS);
        result.setMsg("删除成功");
        return result;
    }
}
